<template>
  <div class="excel-box">
    <el-button
      :type="type?type:'info'"
      plain
      icon="el-icon-upload2"
      :size="size"
      :disabled="disabled"
      @click="dialogImport = true;">{{ btnname }}</el-button>
    <!-- dialogImport start -->
    <el-dialog
      :title="btnname"
      class="dialog-import"
      width="480px"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogImport">
      <slot name="excel"></slot>
      <el-upload
        ref="upload"
        class="coding-import"
        drag
        accept=".xls,.xlsx"
        :limit="1"
        :action="url"
        :http-request="importCode"
        :before-upload="beforeUploadFile">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogImport = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- dialogImport end -->
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'DgImportExcel',
  // {name: 按钮名; type: 按钮类型; size: 尺寸; disabled: 禁用; url: 导入地址}
  // url必传
  props: {
    name: String,
    type: String,
    size: String,
    disabled: Boolean,
    url: String,
    timeout: Number,
    refresh: Boolean
  },
  // props: ['name', 'type', 'size', 'disabled', 'url', 'timeout', 'refresh'],
  data () {
    return {
      btnname: this.name || '导入',
      dialogImport: false
    };
  },
  methods: {
    /**
      * @date 2021/06/29
      * @author wolfMan
      * @description {上传之前校验}
    */
    beforeUploadFile (_content) {
      let _file = _content.name;
      let extension = _file.substring(_file.lastIndexOf('.') + 1);
      if (extension !== 'xls' && extension !== 'xlsx') {
        this.$msgWarning('只能上传后缀为xls、xlsx的文件');
      };
      return extension === 'xls' || extension === 'xlsx';
    },
    /**
      * @date 2021/06/29
      * @author wolfMan
      * @description {文件上传请求接口}
    */
    importCode (_content) {
      let _params = new FormData();
      _params.append('file', _content.file);
      request({
        url: this.url,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        method: 'post',
        timeout: this.timeout || 60000,
        data: _params
      }).then(response => {
        if (response && response.success) {
          let _useData = response.data;
          // result: 1:全部成功；2: 部分成功
          if (_useData.result === 2) {
            this.$confirm(`当前有${_useData.failCount}条数据导入失败,是否下载失败数据！`, '提示', {
              confirmButtonText: '下载',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let blob = this.base64ToBlob(_useData.failFileBase64);
              if ('download' in document.createElement('a')) {
                // 非IE下载
                const elink = document.createElement('a');
                elink.download = _useData.fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
              } else {
                // IE10+下载
                navigator.msSaveBlob(blob, _useData.fileName);
              };
              this.dialogImport = false;
              // 列表页面需要刷新
              if (this.refresh) {
                this.$parent.search();
              };
            }).catch(() => {
              console.log('取消');
              this.dialogImport = false;
            });
          } else {
            this.$msgSuccess('导入成功');
            this.dialogImport = false;
            // 列表页面需要刷新
            if (this.refresh) {
              this.$parent.search();
            };
          };
        } else {
          this.$msgError(response.msg);
        };
      }).always(() => {
        // 清空上传列表
        this.$refs.upload.clearFiles();
      });
    },
    /**
      * @date 2021/07/05
      * @author wolfMan
      * @description {base64转blob}
    */
    base64ToBlob (code) {
      let raw = window.atob(code);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      };
      return new Blob([uInt8Array], { type: 'application/vnd.ms-excel;charset=utf-8' });
    }
  }
};
</script>

<style type="text/scss" lang="scss">
.excel-box {
  float: left;
  line-height: 0;
}
.dialog-import {
  .coding-import {
    padding: 10px;
    text-align: center;
  }
}
</style>